package com.elvin.zoe.parser.im;

import java.util.ArrayList;
import java.util.List;

import com.elvin.zoe.pojo.Message;

public class QqParser  extends ImParser {

	private String date = "";

	@Override
	protected List<String> getMessageTokens(String originalHtml) {
        String messageStartToken = "<tr";
        String messageEndToken = "</tr>";
        List<String> messageTokens = new ArrayList<String>();
        int tokenStart = originalHtml.indexOf(messageStartToken);
		while (tokenStart > 0) {
			int tokenEnd = originalHtml.indexOf(messageEndToken, tokenStart) + messageEndToken.length();
			String messageString = originalHtml.substring(tokenStart, tokenEnd);
			if (messageString.indexOf("<font") > 0){
			    messageString = date + "</date>" + messageString;
				messageTokens.add(messageString);
			}
			if (messageString.indexOf("日期:") > 0){
				date = messageString.substring(messageString.lastIndexOf(":") + 1, messageString.lastIndexOf("</td>")).trim();
			}
            if (messageString.indexOf("Date:") > 0){
                date = messageString.substring(messageString.lastIndexOf(":") + 1, messageString.lastIndexOf("</td>")).trim();
            }
			tokenStart = originalHtml.indexOf(messageStartToken, tokenEnd);
		}
        return messageTokens;
	}

    @Override
    protected int getMessageType(String messageToken) {
        String refined = messageToken.replace("\n", "").toLowerCase();
        if(refined.indexOf("<div style=float:left;margin-right:6px;>.Elvin".toLowerCase()) > 0)
            return Message.OUTGOING;
        else
            return Message.INCOMMING;
    }

    @Override
    protected String getMessageDatetime(String messageToken) {
        String startToken = "</div>";
        int tokenStart = messageToken.indexOf(startToken) + startToken.length();
        int tokenEnd = messageToken.indexOf("</div>", tokenStart);
        String date = messageToken.substring(0, messageToken.indexOf("</date>"));
        return date + " " + messageToken.substring(tokenStart, tokenEnd).replace("&nbsp;", " ");
    }

	@Override
	protected String getMessageDatetimeFormat() {
		return "M/dd/yyyy h:mm:ss a";
	}

    @Override
    protected String getMessageText(String messageToken) {
        String refined = messageToken.replaceAll("【.*WebQQ.*】", "").replaceAll("<br>", " ").replaceAll("&nbsp;", " ");
        refined = refined.replaceAll("<font[^>]*\'>", "").replaceAll("</font>", "").replaceAll("<IMG[^>]*>", "");
        String textStartToken = "<div style=padding-left:20px;>";
        int tokenStart = refined.lastIndexOf(textStartToken) + textStartToken.length();
        int tokenEnd = refined.indexOf("</div>", tokenStart);
        return refined.substring(tokenStart, tokenEnd);
    }

}
